package com.dataaccess.dataaccess.support.udp;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dataaccess.dataaccess.common.base.BaseService;
import com.dataaccess.dataaccess.common.utils.appkit.FirefightingiotKit;
import com.dataaccess.dataaccess.config.rocketmq.UserProducer;
import com.dataaccess.dataaccess.model.AlarmAllDeviceDataChanged;
import com.dataaccess.dataaccess.model.GasAlarmDeviceDataChanged;
import com.dataaccess.dataaccess.model.GasAlarmHttpDeviceDataChanged;
import com.dataaccess.dataaccess.support.utils.MyLogger;
import com.dataaccess.dataaccess.web.mapper.AlarmAllDeviceDataChangedMapper;
import com.dataaccess.dataaccess.web.mapper.GasAlarmDeviceDataChangedMapper;
import com.dataaccess.dataaccess.web.mapper.GasAlarmHttpDeviceDataChangedMapper;
import com.dataaccess.dataaccess.web.service.AsyncService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.Filter;
import org.springframework.integration.annotation.Router;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.ip.udp.UnicastReceivingChannelAdapter;
import org.springframework.messaging.Message;

import javax.annotation.Resource;
import java.util.UUID;

@Configuration
public class DataReceiveConfigration extends BaseService {

    @Resource
    GasAlarmDeviceDataChangedMapper gasAlarmDeviceDataChangedMapper;
    @Resource
    GasAlarmHttpDeviceDataChangedMapper gasAlarmHttpDeviceDataChangedMapper;
    @Resource
    private AlarmAllDeviceDataChangedMapper alarmAllDeviceDataChangedMapper;
    @Resource
    UserProducer userProducer;
    @Resource
    private AsyncService asyncService;
    @Resource
    public MyLogger logger;


    @Bean
    public UnicastReceivingChannelAdapter getUnicastReceivingChannelAdapter() {
        UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(4567);//实例化一个udp 4567端口
        adapter.setOutputChannelName("udp");
        return adapter;
    }

    @Transformer(inputChannel="udp",outputChannel="udpString")
    public String transformer(Message<?> message) {
        return new String((byte[])message.getPayload());//把接收的数据转化为字符串
    }

    @Filter(inputChannel="udpString",outputChannel="udpFilter")
    public boolean filter(String message) {
        logger.info("可燃气设备日志-------------------------------filter"+message+"-------------------------------");
        return true;//如果接收数据开头不是abc直接过滤掉
    }



    @Router(inputChannel="udpFilter")
    public String routing(String message) {
        logger.info("可燃气设备日志-------------------------------routing"+message+"-------------------------------");
        if(message.contains("1")) {//当接收数据包含数字1时
            return "udpRoute1";
        }
        else {
            return "udpRoute2";
        }
    }

    public void mqHandleMes(String message){
        JSONObject jsonParam = null;
        try {
            jsonParam = JSONUtil.parseObj(message);
            jsonParam.put("deviceFlag","udpCombustiblegas");
            String mqFlag = FirefightingiotKit.getStr("mqFlag","mq");
            AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
            alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
            alarmAllDeviceDataChanged.setJsondata(message);
            alarmAllDeviceDataChanged.setType("4");
            alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
            logger.info(mqFlag+"可燃气设备日志-------------------------------mqHandleMes"+message+"-------------------------------");
            if(mqFlag.equals("1")){
                handleMes(message,"udp");
            }else if(mqFlag.equals("3")){
                userProducer.produder(jsonParam.toString());
            }
        }catch (Exception e){
            logger.info("可燃气设备日志--------------------e-----------mqHandleMes"+e.getMessage()+"-------------------------------");
        }


    }


    @ServiceActivator(inputChannel="udpRoute1")
    public void udpMessageHandle(String message) {
        logger.info("可燃气设备日志-------------------------------udpMessageHandle"+message+"-------------------------------");
        //handleMes(message,"udp");
        mqHandleMes(message);
    }


    @ServiceActivator(inputChannel="udpRoute2")
    public void udpMessageHandle2(String message) {
        logger.info("可燃气设备日志-------------------------------udpMessageHandle2"+message+"-------------------------------");
        //handleMes(message,"udp");
        mqHandleMes(message);
    }




//    @Bean
//    public TcpNetServerConnectionFactory getServerConnectionFactory() {
//        TcpNetServerConnectionFactory serverConnectionFactory = new TcpNetServerConnectionFactory(1234);
//        serverConnectionFactory.setSerializer(new ByteArrayRawSerializer());
//        serverConnectionFactory.setDeserializer(new ByteArrayRawSerializer());
//        serverConnectionFactory.setLookupHost(false);
//        return serverConnectionFactory;
//    }
//
//
//    @Bean
//    public TcpReceivingChannelAdapter getReceivingChannelAdapter() {
//        TcpReceivingChannelAdapter receivingChannelAdapter = new TcpReceivingChannelAdapter();
//        receivingChannelAdapter.setConnectionFactory(getServerConnectionFactory());
//        receivingChannelAdapter.setOutputChannelName("tcp");
//        return receivingChannelAdapter;
//    }
//
//
//    @ServiceActivator(inputChannel="tcp")
//    public void messageHandle(Message<?> message) {
//        //报警数据
//        AlarmAllDeviceDataChanged alarmAllDeviceDataChanged = new AlarmAllDeviceDataChanged();
//        alarmAllDeviceDataChanged.setId(UUID.randomUUID().toString());
//        alarmAllDeviceDataChanged.setJsondata(new String((byte[])message.getPayload()));
//        alarmAllDeviceDataChanged.setType("5");
//        alarmAllDeviceDataChangedMapper.insert(alarmAllDeviceDataChanged);
//    }

    public void handleMes(String message,String udp){
        logger.info("可燃气设备日志-------------------------------baojingone"+message+"-------------------------------");
        if(udp.equals("udp")){
            GasAlarmDeviceDataChanged gasAlarmDeviceDataChanged = new GasAlarmDeviceDataChanged();
            gasAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
            gasAlarmDeviceDataChanged.setJsondata(message);
            gasAlarmDeviceDataChangedMapper.insert(gasAlarmDeviceDataChanged);
        }else{
            GasAlarmHttpDeviceDataChanged gasAlarmHttpDeviceDataChanged = new GasAlarmHttpDeviceDataChanged();
            gasAlarmHttpDeviceDataChanged.setId(UUID.randomUUID().toString());
            gasAlarmHttpDeviceDataChanged.setJsondata(message);
            gasAlarmHttpDeviceDataChangedMapper.insert(gasAlarmHttpDeviceDataChanged);
        }
        //数据解析
        JSONObject jsonObject = JSONUtil.parseObj(message);
        String number = jsonObject.getStr("deviceCode");
        String alarmtime = jsonObject.getStr("eventTime");
        String content = null;
        String payloads = jsonObject.getStr("payload").replace("\\","");
        JSONObject payload =new JSONObject(payloads);
        JSONArray jsonArray = payload.getJSONArray("sensor_msg");
        if (jsonArray!=null){
            //存放的报警信息C3H8
            JSONObject jsonObject4 = new JSONObject();
            String name = "";
            for (Object jsonObject1:jsonArray) {
                JSONObject jsonObject2 = JSONUtil.parseObj(jsonObject1);
                if (jsonObject2.get("SensorType").getClass().getName().equals("cn.hutool.json.JSONNull")) {
                    jsonObject4 = jsonObject2;
                    name = "C3H8";
                }else if (jsonObject2.getStr("SensorType").equalsIgnoreCase("C3H8")) {
                    jsonObject4 = jsonObject2;
                    name = "C3H8";
                }else if (jsonObject2.getStr("SensorType").equalsIgnoreCase("CH4")) {
                    jsonObject4 = jsonObject2;
                    name = "CH4";
                }else if (jsonObject2.getStr("SensorType").equalsIgnoreCase("CO")) {
                    jsonObject4 = jsonObject2;
                    name = "一氧化碳";
                }
            }
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("deviceClassify", 4);
            jsonObject3.put("number",number);
            jsonObject3.put("interfaceType","1");
            jsonObject3.put("alarmtime",alarmtime);


            JSONObject jSONObject = new JSONObject();
            JSONArray jSONArray = new JSONArray();
            jSONObject.put("name", "甲烷");
            jSONObject.put("value", jsonObject4.getStr("Value"));
            jSONArray.add(jSONObject);
            JSONObject jsonParamN = new JSONObject();
            jsonParamN.put("paraminfo", jSONArray);
            jsonParamN.put("time", alarmtime);
            jsonParamN.put("number", number);

            switch (jsonObject4.getInt("SensorState")) {
                case 0: // 0：预热
                    if(StrUtil.isNotBlank(name)){
                        logger.info("可燃气设备日志-------------------------------yure"+jsonParamN.toString()+"-------------------------------");
                        restPostOrGet(jsonParamN, "firefightingiot_data", "normalInfo", "device","post");
                        //大数据
                        jsonParamN.put("dataType", "2");
                        restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo","post");
                    }
                    break;
                case 1: // 1:正常
                    if(StrUtil.isNotBlank(name)){
                        logger.info("可燃气设备日志-------------------------------zhengchang"+jsonParamN.toString()+"-------------------------------");
                        restPostOrGet(jsonParamN, "firefightingiot_data", "normalInfo", "device","post");
                        //大数据
                        jsonParamN.put("dataType", "2");
                        restPostOrGet(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo","post");
                        jsonParamN.put("state","1");
                        asyncService.updateDeviceCurrentState(jsonParamN);
                    }
                    break;
                case 4: // 4：故障
                    content = "可燃气体设备故障"+jsonObject4.getStr("Value")+jsonObject4.getStr("Unit");
                    jsonObject3.put("content",content);
                    jsonObject3.put("alarmTypeName","可燃气体设备故障");
                    logger.info("可燃气设备日志-------------------------------故障"+jsonObject3.toString()+"-------------------------------");
                    restPostOrGet(jsonObject3, "communication", "notificationAlarmHandel", "alarmInfo","post");
                    //异步更新设备状态
                    jsonParamN.put("state","4");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                    break;
                case 17: //17:低电量
                    content = "可燃气体设备低电量"+jsonObject4.getStr("Value")+jsonObject4.getStr("Unit");
                    jsonObject3.put("content",content);
                    jsonObject3.put("alarmTypeName","可燃气体设备低电量");
                    logger.info("可燃气设备日志-------------------------------低电量"+jsonObject3.toString()+"-------------------------------");
                    restPostOrGet(jsonObject3, "communication", "notificationAlarmHandel", "alarmInfo","post");
                    //异步更新设备状态
                    jsonParamN.put("state","4");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                    break;
                case 32: //32：报警
                    content = "可燃气设备"+name+"报警"+jsonObject4.getStr("Value")+jsonObject4.getStr("Unit");
                    jsonObject3.put("content",content);
                    jsonObject3.put("alarmTypeName","可燃气设备"+name+"报警");
                    logger.info("可燃气设备日志-------------------------------baojing"+jsonObject3.toString()+"-------------------------------");
                    restPostOrGet(jsonObject3, "communication", "notificationAlarmHandel", "alarmInfo","post");
                    //异步更新设备状态
                    jsonParamN.put("state","2");
                    asyncService.updateDeviceCurrentState(jsonParamN);
                    break;
            }
        }
    }

    public static void main(String[] args) {
        String aa = "{\"dev_id\":\"332006011384\",\"dev_msg\":{\"DeviceType\":\"B204\",\"HardVer\":\"0.5.1.0\",\"SoftVer\":\"0.2.0.0\",\"SwitchAmount\":2,\"SerialPortAmount\":3},\"control_msg\":[{\"ControlId\":\"01\",\"ControlType\":\"Pulse electromagnetic valve\",\"ValueType\":0,\"ControlAmountLowBound \":0,\"ControlAmountBound\":1,\"ControlAmount\":0.0,\"unit\":\"\"}],\"sensor_msg\":[{\"SensorNo\":\"01\",\"SensorType\":null,\"SensorState\":32,\"Value\":7.0,\"Unit\":\"m/s\"},{\"SensorNo\":\"02\",\"SensorType\":\"Signal strength\",\"SensorState\":1,\"Value\":5.0,\"Unit\":\"\"},{\"SensorNo\":\"03\",\"SensorType\":\"Communication Module type\",\"SensorState\":1,\"Value\":1.0,\"Unit\":\"\"}]}";
        JSONObject jsonObject33 = JSONUtil.parseObj(aa);
        JSONArray jsonArray = jsonObject33.getJSONArray("sensor_msg");
        if (jsonArray!=null) {
            //存放的报警信息C3H8
            JSONObject jsonObject4 = new JSONObject();
            String name = "";
            for (Object jsonObject1 : jsonArray) {
                JSONObject jsonObject2 = JSONUtil.parseObj(jsonObject1);
                System.out.println(jsonObject2.get("SensorType").getClass().getName());
                System.out.println(jsonObject2.get("SensorType") != null);
                if (jsonObject2.get("SensorType").getClass().getName().equals("cn.hutool.json.JSONNull")) {
                    jsonObject4 = jsonObject2;
                    name = "C3H8";
                }else if (jsonObject2.getStr("SensorType").equalsIgnoreCase("C3H8")) {
                    jsonObject4 = jsonObject2;
                    name = "C3H8";
                } else if (jsonObject2.getStr("SensorType").equalsIgnoreCase("CH4")) {
                    jsonObject4 = jsonObject2;
                    name = "CH4";
                } else if (jsonObject2.getStr("SensorType").equalsIgnoreCase("CO")) {
                    jsonObject4 = jsonObject2;
                    name = "一氧化碳";
                }
            }
        }
    }
}
